{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "_llm = ChatOpenAI(\n",
    "    api_key=\"ollama\",\n",
    "    model=\"qwen2.5:7b\",\n",
    "    base_url=\"http://192.168.10.13:60001/v1\",\n",
    "    temperature=0.7,\n",
    ")\n",
    "\n",
    "from typing import Annotated\n",
    "from langchain_core.tools import tool\n",
    "\n",
    "\n",
    "@tool\n",
    "def weather(city: Annotated[str, \"被查询的城市,用中文输入\"]) -> str:\n",
    "    \"\"\"\n",
    "    用于查询输入城市今日的天气状况\n",
    "    \"\"\"\n",
    "    if city == \"上海\":\n",
    "        return \"上海今天台风12级\"\n",
    "    else:\n",
    "        return \"天气晴朗风和日丽\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'messages': [HumanMessage(content='今天上海的天气如何？', additional_kwargs={}, response_metadata={}, id='aacfe795-60d4-43ef-bbc5-2e7553fa032a'),\n",
       "  AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_ced59qtn', 'function': {'arguments': '{\"city\":\"上海\"}', 'name': 'weather'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 19, 'prompt_tokens': 167, 'total_tokens': 186, 'completion_tokens_details': None}, 'model_name': 'qwen2.5:7b', 'system_fingerprint': 'fp_ollama', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-7d3add2b-c94c-4533-9605-82986234552f-0', tool_calls=[{'name': 'weather', 'args': {'city': '上海'}, 'id': 'call_ced59qtn', 'type': 'tool_call'}], usage_metadata={'input_tokens': 167, 'output_tokens': 19, 'total_tokens': 186, 'input_token_details': {}, 'output_token_details': {}}),\n",
       "  ToolMessage(content='上海今天台风12级', name='weather', id='633a3d04-70cd-4231-8e53-28e52b1e6921', tool_call_id='call_ced59qtn'),\n",
       "  AIMessage(content='上海今天有台风，级别达到12级，请注意安全，尽量待在室内。', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 20, 'prompt_tokens': 209, 'total_tokens': 229, 'completion_tokens_details': None}, 'model_name': 'qwen2.5:7b', 'system_fingerprint': 'fp_ollama', 'finish_reason': 'stop', 'logprobs': None}, id='run-275bfb7d-d089-4e55-86f7-ca58444ad608-0', usage_metadata={'input_tokens': 209, 'output_tokens': 20, 'total_tokens': 229, 'input_token_details': {}, 'output_token_details': {}})]}"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langgraph.prebuilt import create_react_agent\n",
    "from langchain_core.messages import HumanMessage\n",
    "\n",
    "_agent_executor = create_react_agent(\n",
    "    _llm,\n",
    "    [\n",
    "        weather,\n",
    "    ],\n",
    ")\n",
    "rep = _agent_executor.invoke({\"messages\": [HumanMessage(\"今天上海的天气如何？\")]})\n",
    "\n",
    "rep[\"messages\"][-1].content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.messages import HumanMessage\n",
    "\n",
    "store = [HumanMessage(\"请记住我叫张三\")]\n",
    "rep = _llm.invoke(store)\n",
    "store.append(rep)\n",
    "store.append(HumanMessage(\"我是谁？\"))\n",
    "rep = _llm.invoke(store)\n",
    "rep"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.chat_message_histories import ChatMessageHistory\n",
    "\n",
    "_store = {}\n",
    "\n",
    "\n",
    "def get_session_history(session_id):\n",
    "    if session_id not in _store:\n",
    "        _store[session_id] = ChatMessageHistory()\n",
    "\n",
    "    return _store[session_id]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
    "\n",
    "_message = ChatPromptTemplate(\n",
    "    [\n",
    "        (\"system\", \"请用中文帮助用户\"),\n",
    "        MessagesPlaceholder(variable_name=\"history_contents\"),\n",
    "        (\"human\", \"{content}\"),\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.output_parsers import StrOutputParser\n",
    "\n",
    "_chain = _message | _llm | StrOutputParser()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.runnables import RunnableWithMessageHistory\n",
    "\n",
    "_his_chain = RunnableWithMessageHistory(\n",
    "    _chain,\n",
    "    get_session_history,\n",
    "    input_messages_key=\"content\",\n",
    "    history_messages_key=\"history_contents\",\n",
    ")\n",
    "\n",
    "rep01 = _his_chain.invoke({\"content\":\"请记住我叫张三\"},config={\"configurable\":{\"session_id\"}})"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python310",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
